<!-- 线索标签信息修改弹窗 -->
<script>
import { updateLeads } from './api'
import { getAllTags } from '@/api/portrait'
export default {
  name: '',
  props: {
    value: {},
    leadData: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {},
  data() {
    return {
      addTag: [],
      alllabel: [],
    }
  },
  computed: {},
  watch: {
    // leadData: {
    //   handler(val) {
    //     let ids = val.labelsIds.split(',')
    //     let names = val.labelsNames.split(',')
    //     this.addTag = ids.map((e, i) => ({
    //       id: e,
    //       name: names[i],
    //     }))
    //   },
    //   immediate: true,
    // },
    value: {
      handler(val) {
        val && this.labelEdit()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getAllTags(type) {
      this.$toast.loading({
        message: 'loading...',
        duration: 0,
        forbidClick: true,
      })
      let params = {
        groupTagType: 1,
      }
      if (type === 'person') {
        params = {
          groupTagType: 3,
          userId: this.userId,
        }
      }
      return getAllTags(params)
        .then(({ data }) => {
          this.alllabel = this.listTagOneArray = data

          if (this.editLabelType !== 'person') {
            this.listTagOneArray = []
            data.forEach((element) => {
              element.weTags.forEach((d) => {
                this.listTagOneArray.push(d)
              })
            })
          }
          this.$toast.clear()
        })
        .catch((err) => {
          console.log(err)
          this.$toast.clear()
        })
    },
    async labelEdit(type) {
      // this.editLabelType = type
      await (this.alllabel?.length || this.getAllTags(type))
      this.addTag = []

      // let tags = this.form[type === 'person' ? 'personTags' : 'tags']

      let ids = this.leadData.labelsIds.split(',')
      let names = this.leadData.labelsNames.split(',')
      let tags = ids.map((e, i) => ({
        tagId: e,
        name: names[i],
      }))

      let hasErrorTag = [] // 异常或已经删除的标签
      // let repeat = [] // 重复的标签
      tags &&
        tags.forEach((unit) => {
          // 判断是否有重复标签
          // let isRepeat = this.listTagOneArray.some((d) => {
          //   return d.tagId === unit.tagId
          // })
          // // 去重
          // if (isRepeat) {
          //   repeat.push(unit.name)
          //   return
          // }
          let filter = this.listTagOneArray.find((d) => {
            return d.tagId === unit.tagId
          })
          // 如果没有匹配到，则说明该便签处于异常状态，可能已被删除或破坏
          if (!filter) {
            hasErrorTag.push(unit.name)
            return
          }

          this.addTag.push(filter)
        })
      // 获取用户当前的lable,将当前用户的lable与所有lable进行对比，相同的弹框内蓝色展示
      // 弹框内的标签组选中时蓝色展示
      // 弹框内的子标签与选中时蓝色展示，点击时
    },
    // 点击选择标签
    clickLabel(item) {
      let index = this.addTag.findIndex((e) => {
        return item.tagId == e.tagId
      })
      // 数组里不存在该对象,则添加
      if (index == -1) {
        this.addTag.push({
          groupId: item.groupId,
          name: item.name,
          tagId: item.tagId,
        })
      } else {
        // 数组里存在该对象,则删除
        this.addTag.splice(index, 1)
      }
    },
    // 提交信息
    submit() {
      const toast = this.$toast.loading()
      let params = {
        leadId: this.leadData.id,
        labelsIds: this.addTag.map((e) => e.tagId).join(','),
      }
      updateLeads(params).then((res) => {
        this.cancel()
        toast.clear()
        this.$emit('success')
        this.$toast.success('操作成功')
      })
    },

    cancel() {
      this.$emit('input', false)
    },
  },
}
</script>

<template>
  <van-action-sheet
    v-bind="$attrs"
    v-model="value"
    title="修改标签"
    round
    position="bottom"
    :closeable="false"
    :close-on-click-overlay="false"
  >
    <div class="content">
      <div v-for="(item, index) in alllabel" :key="index">
        <div class="mb15 mt5 tag-group-name">{{ item.groupName }}</div>
        <div class="labelstyle">
          <div
            v-for="(unit, unique) in item.weTags"
            :key="unique"
            class="label"
            :class="addTag.some((e) => e.tagId == unit.tagId) && 'active'"
            @click="clickLabel(unit)"
          >
            {{ unit.name }}
          </div>
        </div>
      </div>

      <van-empty v-if="!alllabel || !alllabel.length" image-size="50" description="暂无数据" />
    </div>
    <div class="footer flex" style="margin: 20px;">
      <van-button class="" native-type="button" round block plain @click="cancel">取消</van-button>
      <van-button type="info" native-type="submit" round block class="ml10" @click="submit">提交</van-button>
    </div>
  </van-action-sheet>
</template>

<style lang="less" scoped>
.content {
  max-height: 60vh;
  position: relative;
  margin: 15px 0 0;
  padding: 0 16px;
  overflow: auto;

  .add-person-tag {
    color: @color;
    font-size: 13px;
    margin: 30px 0;
  }
  .tag-group-name {
    font-size: 14px;
    color: #666;
  }
}
.labelstyle {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  .label {
    display: inline-block;
    min-width: 72px;
    font-size: 13px;
    padding: 4px 5px 3px;
    border-radius: 8px;
    color: #666;
    background: #fafafa;
    text-align: center;
    margin: 0 0 11px 9px;
    line-height: 26px;
  }
  .active {
    background: #ecf5ff;
    color: @color;
  }
}
</style>
